import { Tooltip } from 'antd';
import styles from './index.less';

const tableColumnsObj = {
  // 黑龙江
  PDBLJ: (lock = false) => [
    {
      code: 'statementSubjectCode',
      align: 'center',
      name: '结算科目编号',
      width: 80,
      lock: lock,
      tooltip: true,
    },
    {
      code: 'statementSubjectName',
      name: '结算科目',
      width: 80,
      align: 'center',
      lock: lock,
      tooltip: true,
    },
    {
      code: 'contractSequence',
      align: 'center',
      name: '合同序列',
      width: 140,
      lock: lock,
      tooltip: true,
    },
    {
      code: 'contractName',
      name: '合同名称',
      width: 100,
      align: 'center',
    },
    {
      name: '结算对象',
      code: 'stationObject',
      align: 'center',
      width: 100,
    },
    {
      code: 'contractPeriod',
      align: 'center',
      name: '合同时段',
      width: 100,
    },
    {
      code: 'planContractElectricity',
      align: 'center',
      name: '交易计划电量/合同电量',
      width: 100,
    },
    {
      code: 'settlementElectricityCapacity',
      align: 'center',
      name: '结算电量/容量',
      width: 100,
    },
    {
      code: 'statementPrice',
      align: 'center',
      name: '结算电价',
      width: 100,
    },
    {
      code: 'statementCost',
      align: 'center',
      name: '结算电费',
      width: 100,
    },
  ],
  // 默认 山西
  defaultColumns: (lock = false) => [
    {
      code: 'statementCode',
      name: '结算编号',
      width: 80,
      align: 'center',
      lock: lock,
      tooltip: true,
    },
    {
      code: 'statementTypeName',
      name: '结算类型',
      align: 'center',
      lock: lock,
      width: 140,
      tooltip: true,
    },
    {
      code: 'statementPrice',
      name: '结算单价(元/MWh)',
      width: 100,
      align: 'center',
    },
    {
      code: 'statementSubsidyPrice',
      align: 'center',
      name: '补贴单价(元/MWh)',
      width: 100,
    },
    {
      code: 'statementQuantity',
      align: 'center',
      name: '结算电量(MWh)',
      width: 100,
    },
    {
      code: 'statementCost',
      align: 'center',
      name: '结算电费(元)',
      width: 100,
    },
    {
      name: '合同时段',
      code: 'contractTimeFrame',
      align: 'center',
      width: 100,
    },
    {
      name: '补贴结算收入(元)',
      code: 'statementSubsidyIncome',
      align: 'center',
      width: 100,
      render: (value) => {
        return value ? value.toFixed(2) : 0;
      },
    },
    {
      code: 'statementOtherCost',
      align: 'center',
      name: '其他结算费用(元)',
      width: 100,
    },
    {
      name: '总结算收入-不含补贴（元）',
      code: 'statementEnergyIncome',
      align: 'center',
      width: 150,
    },
    {
      name: '总结算收入-含补贴（元）',
      code: 'statementTotalIncome',
      align: 'center',
      width: 150,
    },
    {
      name: '结算状态',
      code: 'statusName',
      align: 'center',
      width: 80,
    },
    {
      name: '增值税率(%)',
      code: 'taxRate',
      align: 'center',
      width: 80,
    },
  ],
  // 陕西
  PXBSX: (lock = false) => [
    {
      code: 'statementSubjectCode',
      name: '结算科目编码',
      width: 80,
      align: 'center',
      lock: lock,
      tooltip: true,
    },
    {
      code: 'statementSubjectName',
      name: '结算科目',
      width: 80,
      align: 'center',
      lock: lock,
      tooltip: true,
    },
    {
      code: 'contractSequence',
      name: '合同序列',
      width: 140,
      align: 'center',
      lock: lock,
      tooltip: true,
    },
    {
      code: 'contractName',
      name: '合同名称',
      width: 100,
      align: 'center',
      tooltip: true,
    },
    {
      code: 'planContractElectricity',
      name: '合同电量',
      width: 100,
      align: 'center',
      tooltip: true,
    },
    {
      code: 'settlementElectricityCapacity',
      name: '结算电量(MWh)',
      width: 100,
      align: 'center',
      tooltip: true,
    },
    {
      code: 'statementPrice',
      name: '结算均价(元/MWh)',
      width: 150,
      align: 'center',
      tooltip: true,
    },
    {
      code: 'statementCost',
      name: '结算电费(元)',
      width: 120,
      align: 'center',
      tooltip: true,
    },
    {
      code: 'statementUnitName',
      name: '结算单元',
      width: 100,
      align: 'center',
      tooltip: true,
    },
    {
      code: 'adjustMonth',
      name: '调整月份',
      width: 100,
      align: 'center',
      tooltip: true,
    },
    {
      code: 'fileMonth',
      name: '结算单月份',
      width: 100,
      align: 'center',
      tooltip: true,
    },
  ],
};

// 列表配置
export const tableColumns = (marketId) => {
  const centerColumns = tableColumnsObj[marketId]
    ? tableColumnsObj[marketId](true)
    : tableColumnsObj['defaultColumns'](true);
  return [
    {
      code: 'stationName',
      name: '交易单元',
      align: 'left',
      width: 140,
      lock: true,
      features: { autoRowSpan: true },
    },
    ...centerColumns,
    {
      code: 'remark',
      name: '备注',
      align: 'center',
      width: 180,
      tooltip: true,
    },
  ];
};

// 日志配置
export const tabTableColumns = (marketId) => {
  const centerColumns = tableColumnsObj[marketId]
    ? tableColumnsObj[marketId](false)
    : tableColumnsObj['defaultColumns'](false);
  return [
    {
      code: 'stationName',
      name: '交易单元',
      align: 'center',
      width: 140,
      tooltip: true,
    },
    ...centerColumns,
    {
      code: 'remark',
      name: '备注',
      align: 'center',
      width: 180,
      tooltip: true,
    },
  ];
};

export const tabTableDataSource = {
  code: 'dataSourceFlag',
  name: '-',
  align: 'center',
  width: 140,
  tooltip: true,
  // lock: true,
};

export const getColumns = ({ edit, del, marketId }) => {
  const newTableColumns = [];
  tableColumns(marketId).forEach((col) => {
    if (!_.isFunction(col.render)) {
      col.render = (value) => {
        const str = value || value === 0 ? value : value === undefined ? '' : '-';
        return col.tooltip && value ? (
          <Tooltip placement="top" title={str}>
            <div className={styles.textover}>{str}</div>
          </Tooltip>
        ) : (
          str
        );
      };
    }
    newTableColumns.push(col);
  });
  newTableColumns.push({
    name: '操作',
    code: 'operate',
    align: 'center',
    lock: true,
    width: 100,
    render: (value, record, rowIndex) => {
      return !record.id || record.id < 0 ? (
        ''
      ) : (
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <span
            key="delect"
            style={{
              borderRight: '1px solid var(--bd-a50)',
              paddingRight: '10px',
              height: '14px',
              display: 'flex',
              alignItems: 'center',
              color: 'var(--font-primary)',
              cursor: 'pointer',
            }}
            onClick={() => del(record, rowIndex)}
          >
            删除
          </span>
          <span
            key="edit"
            style={{
              padding: '0 10px',
              height: '14px',
              display: 'flex',
              alignItems: 'center',
              color: 'var(--font-primary)',
              cursor: 'pointer',
            }}
            onClick={() => edit(record, rowIndex)}
          >
            编辑
          </span>
        </div>
      );
    },
  });
  return newTableColumns;
};

export const getTreeByCodes = (codes = [], data = []) => {
  const allKeys = [];

  const fn = (opt, i) => {
    const code = codes[i];
    const options = [];
    const id = `${code}Id`;
    const name = `${code}Name`;
    const groupedOpt = _.groupBy(opt, name);

    Object.keys(groupedOpt).forEach((key) => {
      const firstElement = groupedOpt[key][0];
      const temp = {
        ...firstElement,
        label: firstElement[name],
        value: firstElement[id],
      };
      if (code === 'group') {
        temp.key = `${code}_${_.uniqueId()}`;
      }
      if (i !== codes.length - 1) {
        temp.children = fn(groupedOpt[key], i + 1);
      } else {
        allKeys.push(firstElement[id]);
      }
      options.push(temp);
    });

    return options;
  };

  return { treeOptions: fn(data, 0), allKeys };
};

export const fmtRes = (res) => {
  const { dataList, totalBody } = res || {};
  if (!dataList?.length) return [];
  let total = {
    ...totalBody,
    stationName: '结算月份 合计',
    statementCode: '--',
    statementTypeName: '--',
    taxRate: '--',
    statementPrice: truncateToTwoDecimals(totalBody.statementPrice),
    statementCost: truncateToTwoDecimals(totalBody.statementCost),
    planContractElectricity: truncateToTwoDecimals(totalBody.planContractElectricity, 1000),
    settlementElectricityCapacity: truncateToTwoDecimals(
      totalBody.settlementElectricityCapacity,
      1000,
    ),
  };
  let bodys = dataList.map((x) => ({
    ...x,
    stationName: x.statementMonth,
    tableId: x.statementMonth,
  }));

  function truncateToTwoDecimals(num, fixed = 100) {
    if (isNaN(num)) return num;
    return Math.floor(num * fixed) / fixed;
  }

  function formatChildren(list) {
    return list.map((item) => {
      if (item.children && item.children.length > 0) {
        return {
          ...item,
          statementPrice: truncateToTwoDecimals(item.statementPrice),
          statementCost: truncateToTwoDecimals(item.statementCost),
          planContractElectricity: truncateToTwoDecimals(item.planContractElectricity, 1000),
          settlementElectricityCapacity: truncateToTwoDecimals(
            item.settlementElectricityCapacity,
            1000,
          ),
          children: formatChildren(item.children),
        };
      }
      return {
        ...item,
        statementPrice: truncateToTwoDecimals(item.statementPrice),
        statementCost: truncateToTwoDecimals(item.statementCost),
        planContractElectricity: truncateToTwoDecimals(item.planContractElectricity, 1000),
        settlementElectricityCapacity: truncateToTwoDecimals(
          item.settlementElectricityCapacity,
          1000,
        ),
      };
    });
  }
  bodys = formatChildren(bodys);
  return [total, ...bodys];
};
